<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', marginTop:'-16px', minHeight: '280px' }">
`    <div class="about">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <a-input-search
            v-model:value="searchKeyword"
            placeholder="请搜索"
            enter-button="搜索"
            @search="handleSearch"
        />
        <a-button type="primary" @click="showModal1">
          新增
        </a-button>
      </a-space>
      <a-table :columns="columns" :row-key="item => item.userId" :data-source="users" :pagination="pagination"
               :loading="isLoading" @change="handleTableChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'avatar_url'">
            <img :src="record.avatarUrl" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;"/>
            <div v-if="!record.avatarUrl">头像链接为空</div>
          </template>
          <template v-if="column.dataIndex === 'user_type'">
            <span>{{ record.userType }}</span>
          </template>
          <template v-if="column.dataIndex === 'is_active'">
            <span>{{ record.isActive ? '激活' : '未激活' }}</span>
          </template>
          <template v-if="column.dataIndex === 'created_at'">
            <span>{{ formatDate(record.createdAt) }}</span>
          </template>
          <template v-if="column.dataIndex === 'updated_at'">
            <template v-if="!record.updatedAt">
              暂无更新记录
            </template>
            <template v-else>
              <span>{{ formatDate(record.updatedAt) }}</span>
            </template>
          </template>
          <template v-if="column.dataIndex === 'last_login'">
            <template v-if="!record.lastLogin">
              暂无登录记录
            </template>
            <template v-else>
            <span>{{ formatDate(record.lastLogin) }}</span>
            </template>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="showModal(record)">
                编辑
              </a-button>
              <a-popconfirm
                  title="是否确认要删除?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteUser(record)"
              >
                <a-button danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
`  </a-layout-content>
  <!-- 模态框 更新-->
  <a-modal v-model:open="open" title="编辑用户" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form ref="editForm" :model="selectedUser" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="selectedUser.username" />
      </a-form-item>
      <a-form-item label="电子邮件">
        <a-input v-model:value="selectedUser.email" />
      </a-form-item>
      <a-form-item label="电话">
        <a-input v-model:value="selectedUser.phone" />
      </a-form-item>
      <a-form-item label="用户类型" name="user_type">
        <a-select v-model:value="selectedUser.user_type" style="width: 100%">
          <a-select-option value="recruiter">recruiter</a-select-option>
          <a-select-option value="job_seeker">job_seeker</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="头像">
        <img :src="selectedUser.avatar_url" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;" />
        <a-input v-model:value="selectedUser.avatar_url" />
      </a-form-item>
      <a-form-item label="创建时间">
        <a-date-picker v-model:value="selectedUser.created_at" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
      <a-form-item label="最后登录时间">
        <a-date-picker v-model:value="selectedUser.last_login" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
      <a-form-item label="状态">
        <a-switch v-model:checked="selectedUser.is_active" :checked-value="1" :un-checked-value="0" :checked-children="'激活'" :un-checked-children="'未激活'" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 模态框 新增-->
  <a-modal v-model:open="open1" title="新增用户" :confirm-loading="confirmLoading1" @ok="handleOk1">
    <a-form ref="addForm" :model="addUser" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="addUser.username" />
      </a-form-item>
      <a-form-item label="密码">
        <a-input v-model:value="addUser.password_hash" />
      </a-form-item>
      <a-form-item label="电子邮件">
        <a-input v-model:value="addUser.email" />
      </a-form-item>
      <a-form-item label="电话">
        <a-input v-model:value="addUser.phone" />
      </a-form-item>
      <a-form-item label="用户类型" name="user_type">
        <a-select v-model:value="addUser.userType" style="width: 100%">
          <a-select-option value="recruiter">recruiter</a-select-option>
          <a-select-option value="job_seeker">job_seeker</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="头像">
        <img :src="addUser.avatar_url" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;" />
        <a-input v-model:value="addUser.avatarUrl" />
      </a-form-item>
      <a-form-item label="创建时间">
        <a-date-picker v-model:value="addUser.createdAt" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
      <a-form-item label="最后登录时间">
        <a-date-picker v-model:value="addUser.lastLogin" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
      <a-form-item label="状态">
        <a-switch v-model:checked="addUser.isActive" :checked-value="1" :un-checked-value="0" :checked-children="'激活'" :un-checked-children="'未激活'" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
/* eslint-disable */
import { onMounted, ref } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs'; // 使用 dayjs 库来格式化日期
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
// 定义用户数据的类型
interface User {
  userId: number;
  username: string;
  email: string;
  phone: string;
  user_type: string;
  avatar_url: string;
  created_at: string | undefined; // 修改为 string | undefined
  updated_at: string | undefined; // 修改为 string | undefined
  last_login: string | undefined; // 修改为 string | undefined
  is_active: number;
}

// 初始化 selectedUser 为一个空的用户对象
const selectedUser = ref<User>({
  userId: 0,
  username: '',
  email: '',
  phone: '',
  user_type: '',
  avatar_url: '',
  created_at: undefined, // 修改为 undefined
  updated_at: undefined, // 修改为 undefined
  last_login: undefined, // 修改为 undefined
  is_active: 0,
});

const addUser = ref<any>({
  username: '',
  password_hash: '',
  email: '',
  phone: '',
  userType: '',
  avatarUrl: '',
  createdAt: undefined,
  updatedAt: undefined,
  lastLogin: undefined,
  isActive: 0,
});

// 定义表格结构
const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
  },
  {
    title: '电子邮件',
    dataIndex: 'email',
  },
  {
    title: '电话',
    dataIndex: 'phone',
  },
  {
    title: '用户类型',
    dataIndex: 'user_type',
  },
  {
    title: '头像',
    dataIndex: 'avatar_url',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
  },
  {
    title: '最后修改时间',
    dataIndex: 'updated_at',
  },
  {
    title: '最后登录时间',
    dataIndex: 'last_login',
  },
  {
    title: '状态',
    dataIndex: 'is_active',
  },
  {
    title: '操作',
    dataIndex: 'action',
  }
];

// 表格数据
const users = ref<User[]>([]);
interface Pagination {
  current: number;
  pageSize: number;
  total?: number;
  [key: string]: any; // 兼容其他字段
}

// 分页信息
const pagination = ref({
  pageSize: 10, // 设置每页显示10条数据
  total: 0,
  current: 1
});

// 数据加载状态
let isLoading = ref(true);

// 搜索关键字
const searchKeyword = ref('');

// 是否搜索状态
let isSearch = ref(false);

// 日期格式化函数
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 表格分页逻辑
const handleTableChange = (pag: Pagination) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchUsers();
  }
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/users/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    users.value = res.data.data.list;
    if (users.value.length === 0 && pagination.value.current > 1) {
      pagination.value.current = pagination.value.current - 1;
      fetchUsers();
    }
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

onMounted(async () => {
  await fetchUsers();
  window.scrollTo({ top: 0, behavior: 'smooth' });
});

// 弹窗
const modalText = ref<string>('Content of the modal');
const open = ref<boolean>(false);
const open1 = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const confirmLoading1 = ref<boolean>(false);

// 显示弹窗
const showModal = (record: User) => {
  if (record) {
    open.value = true;
    selectedUser.value = {
      userId: record.userId,
      username: record.username,
      email: record.email,
      phone: record.phone,
      user_type: record.userType,
      is_active: record.isActive,
      avatar_url: record.avatarUrl,
      created_at: dayjs(record.createdAt),
      last_login: record.lastLogin ? dayjs(record.lastLogin) : null,
    };
    modalText.value = JSON.stringify(record);
  } else {
    console.error('Invalid record passed to showModal:', record);
  }
};

// 删除用户
const deleteUser = (record: User) => {
  axios.post('/users/delete', {
    userId: record.userId
  }).then(() => {
    if (!isSearch.value) {
      fetchUsers();
    } else {
      handleSearch();
    }
    message.success('删除用户信息成功');
  }).catch(err => {
    console.error('删除用户失败:', err);
    message.error('删除用户失败，请稍后重试');
  });
};

// 修改弹窗确定
const editForm = ref<FormInstance | null>(null);
const handleOk = () => {
  editForm.value?.validateFields().then(() => {
    confirmLoading.value = true;
    setTimeout(() => {
      open.value = false;
      confirmLoading.value = false;
    }, 500);
    axios.post('/users/update', {
      userId: selectedUser.value.userId,
      username: selectedUser.value.username,
      email: selectedUser.value.email,
      phone: selectedUser.value.phone,
      userType: selectedUser.value.user_type,
      avatarUrl: selectedUser.value.avatar_url,
      createdAt: selectedUser.value.created_at.format('YYYY-MM-DD HH:mm:ss'),
      lastLogin: selectedUser.value.last_login ? selectedUser.value.last_login.format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'), // 如果最后登录日期为空，则填充当前时间
      isActive: selectedUser.value.is_active,
    }).then(res => {
      if (!isSearch.value) {
        fetchUsers();
      } else {
        handleSearch();
      }
      console.log('更新用户信息成功:', res.data);
      message.success('更新用户信息成功');
    }).catch(err => {
      console.error('更新用户失败:', err);
      message.error('更新用户失败，请稍后重试');
    });
  }).catch((errorInfo) => {
    console.log('Failed:', errorInfo);
  });
};

// 新增表单引用
const showModal1 = () => {
  open1.value = true;
  addUser.value = {
    username: '',
    password_hash: '',
    email: '',
    phone: '',
    userType: '',
    avatarUrl: '',
    createdAt: undefined,
    updatedAt: undefined,
    lastLogin: null,
    isActive: 0,
  };
};

const handleOk1 = () => {
  addForm.value?.validateFields().then(() => {
    confirmLoading1.value = true;
    setTimeout(() => {
      open1.value = false;
      confirmLoading1.value = false;
    }, 500);
    axios.post('/users/add', {
      username: addUser.value.username,
      passwordHash: addUser.value.password_hash,
      email: addUser.value.email,
      phone: addUser.value.phone,
      userType: addUser.value.userType,
      avatarUrl: addUser.value.avatarUrl,
      createdAt: addUser.value.createdAt ? addUser.value.createdAt.format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'), // 如果创建时间为空，则填充当前时间
      lastLogin: addUser.value.lastLogin ? addUser.value.lastLogin.format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'), // 如果最后登录日期为空，则填充当前时间
      isActive: addUser.value.isActive,
    }).then(res => {
      if (res.data.code === 200) {
        addUser.value = {
          username: '',
          password_hash: '',
          email: '',
          phone: '',
          userType: '',
          avatarUrl: '',
          createdAt: '',
          updatedAt: '',
          lastLogin: '',
          isActive: 0,
        };
        if (!isSearch.value) {
          fetchUsers();
        } else {
          handleSearch();
        }
        message.success('添加用户信息成功');
      } else {
        message.error(res.data.message);
      }
    }).catch(err => {
      console.error('添加用户失败:', err);
      message.error('添加用户失败，请稍后重试');
    });
  }).catch((errorInfo) => {
    console.log('Failed:', errorInfo);
  });
};

// 搜索逻辑
const handleSearch = () => {
  axios.post('/users/query', {
    username: searchKeyword.value,
    page: pagination.value.current,
    size: pagination.value.pageSize
  }).then(res => {
    pagination.value.current = 1;
    isSearch.value = true;
    pagination.value.total = res.data.data.total;
    users.value = res.data.data;
    isLoading.value = false;
    console.log('搜索用户信息成功:', res.data.data.list);
  }).catch(err => {
    console.error('搜索失败:', err);
    isLoading.value = false;
  });
};

// 验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  // user_type: [
  //   { required: true, message: '请选择用户类型', trigger: 'change' },
  // ],
};
</script>
